package hivi.vn.hivigold.fragment;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.activities.SelectEmployee;
import hivi.vn.hivigold.activities.SelectPartner;
import hivi.vn.hivigold.activities.SelectStock;
import hivi.vn.hivigold.adapters.VoucherAdapter;
import hivi.vn.hivigold.database.Preferences;
import hivi.vn.hivigold.database.WebService;
import hivi.vn.hivigold.objects.Employee;
import hivi.vn.hivigold.objects.Item;
import hivi.vn.hivigold.objects.Partner;
import hivi.vn.hivigold.objects.Stock;
import hivi.vn.hivigold.objects.VoucherDetail;
import hivi.vn.hivigold.objects.VoucherMaster;
import hivi.vn.hivigold.utils.Formats;

import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;

import android.R.bool;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.VpnService;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class VoucherFragment extends Fragment {
	static final int ACTION_NEW = 1;
	static final int ACTION_VIEW = 3;
	static final int ACTION_START = 2;
	public static final String ITEM_SELECTED = "ITEM_SELECTED";
	int CURRENT_ACTION = -1;
	int ACTION_EDIT_ITEM = 1;
	int ACTION_NEW_ITEM = 2;

	static final int SCAN_REQUEST = 4;
	ImageButton imgKhach_hang;
	EditText txtSo_ct;
	EditText txtNgay_ct;
	EditText txtEmployee;
	EditText txtStock;
	EditText txtNote;
	EditText txtBarcode;
	EditText txtMoney;
	EditText txtCk;
	EditText txtTotal;
	TextView tvPartnerName;
	Button btnNew;
	Button btnPrint;
	Button btnSavePrint;
	Button btnDelete;
	Button btnSearch;
	Button btnEnter;
	Button btnScan;
	Button btnSave;
	Button btnCancelV;
	ListView lstVoucher;

	TextView txtNameItem;
	EditText txtTlg_da;
	EditText txtTlg_au;
	EditText txtHlg_au;
	EditText txtTien_da;
	EditText txtTien_cong;
	EditText txtTong_tlg;
	EditText txtGia_au;
	EditText txtGia_ban11;
	EditText txtSo_luong;
	EditText txtThanh_tien;

	RadioButton rboMua;
	RadioButton rboBan;
	Button btnAdd;
	Button btnCancel;
	Button btnCal;

	Date ngay_ct;
	ProgressDialog progressDialog;
	AlertDialog itemDialog;
	ArrayList<VoucherDetail> arrVoucherDetail;
	ArrayList<Item> arrItem;
	VoucherAdapter adapter;
	VoucherMaster master;
	int flagChangeValue = -1;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.voucher_layout, null);
		imgKhach_hang = (ImageButton) v.findViewById(R.id.imgPartner);
		txtSo_ct = (EditText) v.findViewById(R.id.txtSo_ct);
		txtNgay_ct = (EditText) v.findViewById(R.id.txtNgay_ct);
		txtEmployee = (EditText) v.findViewById(R.id.txtEmployee);
		txtStock = (EditText) v.findViewById(R.id.txtStock);
		txtNote = (EditText) v.findViewById(R.id.txtNote);
		txtBarcode = (EditText) v.findViewById(R.id.txtBarcode);
		txtMoney = (EditText) v.findViewById(R.id.txtTien_hang);
		txtCk = (EditText) v.findViewById(R.id.txtCk);
		txtTotal = (EditText) v.findViewById(R.id.txtTotal);
		tvPartnerName = (TextView) v.findViewById(R.id.tvPartnerName);
		btnNew = (Button) v.findViewById(R.id.btnNew);
		btnPrint = (Button) v.findViewById(R.id.btnPrint);
		btnSavePrint = (Button) v.findViewById(R.id.btnSaveAndPrint);
		btnDelete = (Button) v.findViewById(R.id.btnDelete);
		btnSearch = (Button) v.findViewById(R.id.btnSearch);
		btnEnter = (Button) v.findViewById(R.id.btnEnter);
		btnScan = (Button) v.findViewById(R.id.btnScan);
		btnSave = (Button) v.findViewById(R.id.btnSave);
		btnCancelV = (Button) v.findViewById(R.id.btnCancel);
		lstVoucher = (ListView) v.findViewById(R.id.lstVoucher);
		lstVoucher.setOnItemClickListener(onItemClickListener);
		lstVoucher.setOnItemLongClickListener(onItemLongClickListener);
		txtCk.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					callist();
				}
				return false;
			}
		});

		btnNew.setOnClickListener(onClick);
		btnSave.setOnClickListener(onClick);
		btnSavePrint.setOnClickListener(onClick);
		btnPrint.setOnClickListener(onClick);
		btnDelete.setOnClickListener(onClick);
		btnSearch.setOnClickListener(onClick);
		btnEnter.setOnClickListener(onClick);
		btnScan.setOnClickListener(onClick);
		btnCancelV.setOnClickListener(onClick);
		imgKhach_hang.setOnClickListener(onClick);

		txtEmployee.setOnLongClickListener(onLong);
		txtStock.setOnLongClickListener(onLong);
		txtNgay_ct.setOnClickListener(onClick);

		Bundle bundle = getArguments();
		if (bundle != null) {
			Item i = (Item) bundle.getSerializable(ITEM_SELECTED);
			if (i != null) {
				CURRENT_ACTION = ACTION_NEW;
				setAction();
				setValue();
				txtBarcode.setText(i.getVtID());
				showDetailItem();
			}
		} else {
			setAction();
			setValue();
		}
		getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		return v;
	}

	OnItemClickListener onItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			// TODO Auto-generated method stub
			if (CURRENT_ACTION == ACTION_NEW) {
				final int position = arg2;
				Item i = arrItem.get(position);
				VoucherDetail v = arrVoucherDetail.get(position);
				showDialogItem(i, v.getSo_luong(), v.getTien(), v.getCtID1().equals("BANHANG") ? "GIABAN" : "GIAMUA", ACTION_EDIT_ITEM, position);
			}

		}

	};

	OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			// TODO Auto-generated method stub
			if (CURRENT_ACTION == ACTION_NEW) {
				final int position = arg2;
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setMessage(R.string.confirm_ask);
				builder.setTitle(R.string.confirm);

				builder.setNegativeButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						arrItem.remove(position);
						arrVoucherDetail.remove(position);
						adapter.swapData(arrVoucherDetail);
						callist();
						dialog.dismiss();
					}
				});
				builder.setPositiveButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});

				AlertDialog alert = builder.create();
				alert.show();
			}
			return true;
		}
	};

	OnLongClickListener onLong = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
			if (v.getId() == R.id.txtEmployee) {
				Intent i = new Intent(getActivity(), SelectEmployee.class);
				startActivityForResult(i, SelectEmployee.SELECTED_EMPLOYEE_KEY);
			} else if (v.getId() == R.id.txtStock) {
				Intent i = new Intent(getActivity(), SelectStock.class);
				startActivityForResult(i, SelectStock.SELECTED_STOCK_KEY);
			}
			return true;
		}
	};

	OnClickListener onClick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if (arg0.getId() == R.id.btnNew) {
				CURRENT_ACTION = ACTION_NEW;
				setAction();
				setValue();
			} else if (arg0.getId() == R.id.btnScan) {
				Intent i = new Intent("com.google.zxing.client.android.SCAN");
				i.putExtra("SCAN_MODE", "CODE_128");
				startActivityForResult(i, SCAN_REQUEST);
			} else if (arg0.getId() == R.id.btnSave) {
				if (checkValid()) {
					VoucherAsync save = new VoucherAsync(false);
					save.execute("0");
				} else {
					Toast.makeText(getActivity(), R.string.warning_notempty, Toast.LENGTH_LONG).show();
				}
			} else if (arg0.getId() == R.id.btnSaveAndPrint) {
				if (checkValid()) {
					VoucherAsync save = new VoucherAsync(true);
					save.execute();
				} else {
					Toast.makeText(getActivity(), R.string.warning_notempty, Toast.LENGTH_LONG).show();
				}
			} else if (arg0.getId() == R.id.btnPrint) {
				startPrint(master.getStt_rec());
			} else if (arg0.getId() == R.id.btnDelete) {
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setMessage(R.string.confirm_ask);
				builder.setTitle(R.string.confirm);

				builder.setNegativeButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						DeleteVoucherAsync delete = new DeleteVoucherAsync();
						delete.execute(master.getStt_rec(), master.getSo_ct());
					}
				});
				builder.setPositiveButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});

				AlertDialog alert = builder.create();
				alert.show();
			} else if (arg0.getId() == R.id.btnEnter) {
				hideKeyboard();
				showDetailItem();
			} else if (arg0.getId() == R.id.imgPartner) {
				Intent i = new Intent(getActivity(), SelectPartner.class);
				startActivityForResult(i, SelectPartner.SELECTED_PARTNER_KEY);
			} else if (arg0.getId() == R.id.btnCancel) {
				CURRENT_ACTION = ACTION_START;
				setAction();
				setValue();
			} else if (arg0.getId() == R.id.txtNgay_ct) {
				DatePickerDialog mDatePickerDialog = new DatePickerDialog(getActivity(), mDateSetListener, Formats.getComDateNow(ngay_ct, "yyyy"), (Formats.getComDateNow(ngay_ct, "MM") - 1), Formats.getComDateNow(ngay_ct, "dd"));
				mDatePickerDialog.setTitle(R.string.ngay_ct);
				mDatePickerDialog.show();
			}
		}
	};

	void showKeyboard() {
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
			imm.showSoftInput(txtBarcode, 0);
	}

	void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
			imm.hideSoftInputFromWindow(txtBarcode.getWindowToken(), 0);
	}

	private void startPrint(final String stt_rec) {
		View v = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.printtype, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setView(v);
		final AlertDialog alert = builder.create();
		alert.show();
		Button btnTT = (Button) v.findViewById(R.id.btnTT);
		Button btnGdbv = (Button) v.findViewById(R.id.btnGdbv);
		Button btnDiamond = (Button) v.findViewById(R.id.btnDiamond);
		btnGdbv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				alert.dismiss();
				PrintVoucherAsync async = new PrintVoucherAsync(1);
				async.execute(stt_rec);
			}
		});
		btnTT.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				alert.dismiss();
				PrintVoucherAsync async = new PrintVoucherAsync(3);
				async.execute(stt_rec);
			}
		});
		btnDiamond.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				alert.dismiss();
				PrintVoucherAsync async = new PrintVoucherAsync(2);
				async.execute(stt_rec);
			}
		});
	}

	private boolean checkValid() {
		if (master.getFK_doitacID() == null) {
			return false;
		}
		if (master.getFK_bpkdID() == null) {
			return false;
		}
		if (master.getFK_khoID() == null) {
			return false;
		}
		if (arrVoucherDetail.size() == 0) {
			return false;
		}

		callist();

		master.setTien_hang(txtMoney.getText().toString().trim().equals("") ? 0 : Double.valueOf(txtMoney.getText().toString().trim().replace(",", "")));
		master.setT_Sl(txtMoney.getTag() == null ? 0 : Double.valueOf(txtMoney.getTag().toString().trim().replace(",", "")));
		master.setTien_ck(txtCk.getText().toString().trim().equals("") ? 0 : Double.valueOf(txtCk.getText().toString().trim().replace(",", "")));
		master.setT_Tien(txtTotal.getText().toString().trim().equals("") ? 0 : Double.valueOf(txtTotal.getText().toString().trim().replace(",", "")));
		master.setT_Sl(txtMoney.getTag() == null ? 0 : Double.valueOf(txtMoney.getTag().toString().replace(",", "")));
		master.setUser_id0(Preferences.getPreferenceValue(getActivity(), Preferences.CURRENTUSER));
		master.setUser_id2(Preferences.getPreferenceValue(getActivity(), Preferences.CURRENTUSER));
		master.setStatus(Preferences.getPreferenceValue(getActivity(), Preferences.VOUCHERTYPE));
		master.setNgay_ct(Formats.DateFormatInsert(ngay_ct));
		master.setDien_Giai(txtNote.getText().toString());

		return true;
	}

	DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			// TODO Auto-generated method stub
			ngay_ct = Formats.createDate(year, monthOfYear, dayOfMonth);
			txtNgay_ct.setText(Formats.DateFormatDisplay(ngay_ct));
		}
	};

	private void showDetailItem() {
		if (txtBarcode.getText().length() != 0) {
			btnEnter.setFocusable(true);
			View v = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.buysale, null);
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setView(v);
			final AlertDialog alert = builder.create();
			alert.show();
			Button btnSale = (Button) v.findViewById(R.id.btnSale);
			Button btnBuy = (Button) v.findViewById(R.id.btnBuy);
			final String barcode = txtBarcode.getText().toString().trim();
			txtBarcode.setText("");
			btnSale.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					alert.dismiss();
					ItemAsync itemAsync = new ItemAsync(barcode, "GIABAN");
					itemAsync.execute();
				}
			});
			btnBuy.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					alert.dismiss();
					ItemAsync itemAsync = new ItemAsync(barcode, "GIAMUA");
					itemAsync.execute();
				}
			});

		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == getActivity().RESULT_OK) {
			Bundle bundle = data.getExtras();
			switch (requestCode) {
			case SelectPartner.SELECTED_PARTNER_KEY:
				Partner p = (Partner) bundle.getSerializable(SelectPartner.SELECTED_PARTNER);
				tvPartnerName.setText(p.getPartnerID() + "-" + p.getPartnerName());
				Bitmap bm = Formats.creatBitmap(getActivity(), p.getPartnerImage());
				if (bm == null) {
					imgKhach_hang.setImageResource(R.drawable.partnera);
				} else {
					imgKhach_hang.setImageBitmap(bm);
				}
				imgKhach_hang.setTag(p);
				master.setFK_doitacID(p.getPartnerID());
				break;
			case SelectEmployee.SELECTED_EMPLOYEE_KEY:
				Employee e = (Employee) bundle.getSerializable(SelectEmployee.SELECTED_EMPLOYEE);
				txtEmployee.setText(e.getEmployeeName());
				txtEmployee.setTag(e);
				master.setFK_bpkdID(e.getEmployeeID());
				break;
			case SelectStock.SELECTED_STOCK_KEY:
				Stock s = (Stock) bundle.getSerializable(SelectStock.SELECTED_STOCK);
				txtStock.setText(s.getStockName());
				txtStock.setTag(s);
				master.setFK_khoID(s.getStockID());
				break;
			case SCAN_REQUEST:
				txtBarcode.setText(data.getStringExtra("SCAN_RESULT"));
				showDetailItem();
				break;
			}
		}
	};

	private void setAction() {
		switch (CURRENT_ACTION) {
		case ACTION_NEW:
			imgKhach_hang.setEnabled(true);
			txtEmployee.setEnabled(true);
			txtStock.setEnabled(true);
			txtNote.setEnabled(true);
			txtBarcode.setEnabled(true);
			txtMoney.setEnabled(true);
			txtCk.setEnabled(true);
			txtTotal.setEnabled(true);
			txtNgay_ct.setEnabled(true);
			btnScan.setEnabled(true);
			btnEnter.setEnabled(true);

			btnNew.setVisibility(View.GONE);
			btnPrint.setVisibility(View.GONE);
			btnDelete.setVisibility(View.GONE);
			btnSearch.setVisibility(View.GONE);
			btnSavePrint.setVisibility(View.VISIBLE);
			btnSave.setVisibility(View.VISIBLE);
			btnCancelV.setVisibility(View.VISIBLE);
			break;
		case ACTION_VIEW:
			imgKhach_hang.setEnabled(false);
			txtNgay_ct.setEnabled(false);
			txtEmployee.setEnabled(false);
			txtStock.setEnabled(false);
			txtNote.setEnabled(false);
			txtBarcode.setEnabled(false);
			btnScan.setEnabled(false);
			btnEnter.setEnabled(false);
			txtMoney.setEnabled(false);
			txtCk.setEnabled(false);
			txtTotal.setEnabled(false);
			btnScan.setEnabled(false);
			btnEnter.setEnabled(false);

			btnNew.setVisibility(View.VISIBLE);
			btnPrint.setVisibility(View.VISIBLE);
			btnDelete.setVisibility(View.VISIBLE);
			btnSearch.setVisibility(View.GONE);
			btnSavePrint.setVisibility(View.GONE);
			btnSave.setVisibility(View.GONE);
			btnCancelV.setVisibility(View.GONE);
			break;
		default:
			txtNgay_ct.setEnabled(false);
			imgKhach_hang.setEnabled(false);
			txtEmployee.setEnabled(false);
			txtStock.setEnabled(false);
			txtNote.setEnabled(false);
			txtBarcode.setEnabled(false);

			txtMoney.setEnabled(false);
			txtCk.setEnabled(false);
			txtTotal.setEnabled(false);

			btnScan.setEnabled(false);
			btnEnter.setEnabled(false);

			btnNew.setVisibility(View.VISIBLE);
			btnPrint.setVisibility(View.GONE);
			btnDelete.setVisibility(View.GONE);
			btnSearch.setVisibility(View.GONE);
			btnSavePrint.setVisibility(View.GONE);
			btnSave.setVisibility(View.GONE);
			btnCancelV.setVisibility(View.GONE);
			break;
		}
	}

	private void setValue() {
		switch (CURRENT_ACTION) {
		case ACTION_NEW:
			imgKhach_hang.setImageResource(R.drawable.partnera);
			Employee e = new Employee();
			e.setEmployeeID(Preferences.getPreferenceValue(getActivity(), Preferences.EMPLOYEEID));
			e.setEmployeeName(Preferences.getPreferenceValue(getActivity(), Preferences.EMPLOYEENAME));
			Partner p = new Partner();
			p.setPartnerID(Preferences.getPreferenceValue(getActivity(), Preferences.PARTNERID));
			p.setPartnerName(Preferences.getPreferenceValue(getActivity(), Preferences.PARTNERNAME));
			Stock s = new Stock();
			s.setStockID(Preferences.getPreferenceValue(getActivity(), Preferences.STOCKID));
			s.setStockName(Preferences.getPreferenceValue(getActivity(), Preferences.STOCKNAME));
			txtEmployee.setText(e.getEmployeeName());
			txtEmployee.setTag(e);

			txtStock.setText(s.getStockName());
			txtStock.setTag(s);
			tvPartnerName.setText(p.getPartnerName());
			imgKhach_hang.setTag(p);
			txtNote.setText("");
			txtBarcode.setText("");
			txtMoney.setText("");
			txtSo_ct.setText("");
			txtMoney.setTag(null);
			txtCk.setText("");
			txtTotal.setText("");
			ngay_ct = Formats.CurrentDate();
			txtNgay_ct.setText(Formats.DateFormatDisplay(ngay_ct));

			arrVoucherDetail = new ArrayList<VoucherDetail>();
			arrItem = new ArrayList<Item>();
			master = new VoucherMaster();
			master.setFK_bpkdID(e.getEmployeeID());
			master.setFK_khoID(s.getStockID());
			master.setFK_doitacID(p.getPartnerID());
			if (adapter == null) {
				adapter = new VoucherAdapter(getActivity(), arrVoucherDetail);
				lstVoucher.setAdapter(adapter);
			} else {
				adapter.swapData(arrVoucherDetail);
			}
			break;
		case ACTION_VIEW:

			break;
		case ACTION_START:
			txtEmployee.setText("");
			txtEmployee.setTag(null);
			txtStock.setText("");
			txtStock.setTag(null);
			tvPartnerName.setText("");
			imgKhach_hang.setTag(null);
			imgKhach_hang.setImageResource(R.drawable.partnera);
			txtNote.setText("");
			txtBarcode.setText("");
			txtMoney.setText("");
			txtCk.setText("");
			txtTotal.setText("");
			txtSo_ct.setText("");
			txtNgay_ct.setText("");
			arrVoucherDetail = new ArrayList<VoucherDetail>();
			arrItem = new ArrayList<Item>();
			master = new VoucherMaster();
			if (adapter == null) {
				adapter = new VoucherAdapter(getActivity(), arrVoucherDetail);
				lstVoucher.setAdapter(adapter);
			} else {
				adapter.swapData(arrVoucherDetail);
			}
			break;
		}
	}

	private class ItemAsync extends AsyncTask<Void, Void, Item> {
		ProgressDialog dialog;
		Item item;
		String key;
		String muaban;

		public ItemAsync(String key, String muaban) {
			// TODO Auto-generated constructor stub
			this.key = key;
			this.muaban = muaban;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(getActivity());
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected void onPostExecute(Item result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			item = result;
			if (item == null) {
				return;
			}
			showDialogItem(item, Double.valueOf(1), item.getGia_ban11(), muaban, ACTION_NEW_ITEM, 0);
		}

		@Override
		protected Item doInBackground(Void... arg0) {
			// TODO Auto-generated method stub

			return WebService.getItemByID(getActivity(), key, muaban);
		}

	}

	private class VoucherAsync extends AsyncTask<String, Void, VoucherMaster> {
		ProgressDialog dialog;
		Boolean print = true;

		public VoucherAsync(Boolean p) {
			// TODO Auto-generated constructor stub
			print = p;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(getActivity());
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected void onPostExecute(VoucherMaster result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result == null) {
				Toast.makeText(getActivity(), R.string.alert_add_voucher_fail, Toast.LENGTH_LONG).show();
			} else {
				master.setStt_rec(result.getStt_rec());
				master.setSo_ct(result.getSo_ct());
				txtSo_ct.setText(master.getSo_ct());
				Toast.makeText(getActivity(), R.string.alert_add_voucher_success, Toast.LENGTH_LONG).show();
				CURRENT_ACTION = ACTION_VIEW;
				setAction();
				if (print) {
					startPrint(master.getStt_rec());
				}
			}
			dialog.dismiss();
		}

		@Override
		protected VoucherMaster doInBackground(String... arg0) {
			// TODO Auto-generated method stub

			return WebService.saveVoucher(getActivity(), master, arrVoucherDetail);
		}

	}

	private class DeleteVoucherAsync extends AsyncTask<String, Void, Boolean> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(getActivity());
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getActivity(), R.string.alert_delete_voucher_success, Toast.LENGTH_LONG).show();
				CURRENT_ACTION = ACTION_START;
				setValue();
				setAction();
			} else {
				Toast.makeText(getActivity(), R.string.alert_delete_voucher_fail, Toast.LENGTH_LONG).show();
			}
			dialog.dismiss();
		}

		@Override
		protected Boolean doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			return WebService.deleteVoucher(getActivity(), arg0[0], arg0[1]);
		}

	}

	private class PrintVoucherAsync extends AsyncTask<String, Void, Boolean> {
		int printtype = -1;

		public PrintVoucherAsync(int type) {
			// TODO Auto-generated constructor stubt
			printtype = type;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Toast.makeText(getActivity(), R.string.alert_printing, Toast.LENGTH_LONG).show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getActivity(), R.string.alert_print_voucher_success, Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(getActivity(), R.string.alert_print_voucher_fail, Toast.LENGTH_LONG).show();
			}
		}

		@Override
		protected Boolean doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			return this.printtype != -1 ? WebService.printVoucher(getActivity(), arg0[0], printtype) : false;
		}

	}

	private void callist() {
		double tong_sl = 0;
		double tong_tien = 0;
		double ck = 0;
		double thanh_tien = 0;
		for (VoucherDetail v : arrVoucherDetail) {
			tong_tien = (v.getCtID1().equals("MUAHANG") ? -(v.getTien()) : v.getTien()) + tong_tien;
			tong_sl = (v.getCtID1().equals("MUAHANG") ? -(v.getSo_luong()) : v.getSo_luong()) + tong_sl;
		}
		ck = txtCk.getText().toString().trim().length() == 0 ? 0 : Double.valueOf(txtCk.getText().toString().replace(",", ""));
		thanh_tien = tong_tien - ck;
		txtMoney.setText(Formats.money(tong_tien));
		txtMoney.setTag(tong_sl == 0 ? null : tong_sl);
		txtTotal.setText(Formats.money(thanh_tien));
	}

	private double get_GiaAU(final String itemid, final String muaban) {
		Item giaAu = WebService.getGiaAU(getActivity(), itemid, muaban);
		return giaAu.getGia_ban11();
	}

	private void showDialogItem(final Item item, Double soluong, Double thanhtien, final String muaban, final int action, final int position) {
		View v = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.voucheritem, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setView(v);
		txtNameItem = (TextView) v.findViewById(R.id.tvNameItem);
		txtTlg_da = (EditText) v.findViewById(R.id.txtTlg_da);
		txtTlg_au = (EditText) v.findViewById(R.id.txtTlg_au);
		txtHlg_au = (EditText) v.findViewById(R.id.txtHlg_au);
		txtTien_da = (EditText) v.findViewById(R.id.txtTien_da);
		txtTien_cong = (EditText) v.findViewById(R.id.txtTien_cong);
		txtTong_tlg = (EditText) v.findViewById(R.id.txtTong_tlg);
		txtGia_au = (EditText) v.findViewById(R.id.txtGia_au);
		txtGia_ban11 = (EditText) v.findViewById(R.id.txtGia_ban11);
		txtSo_luong = (EditText) v.findViewById(R.id.txtSo_luong);
		txtThanh_tien = (EditText) v.findViewById(R.id.txtThanh_tien);
		rboMua = (RadioButton) v.findViewById(R.id.rboBuy);
		rboBan = (RadioButton) v.findViewById(R.id.rboSale);
		btnAdd = (Button) v.findViewById(R.id.btn_add);
		btnCancel = (Button) v.findViewById(R.id.btn_cancel);
		btnCal = (Button) v.findViewById(R.id.btnCal);

		txtSo_luong.setText(Formats.number(soluong));
		txtNameItem.setText(item.getVtName());
		txtTlg_au.setText(Formats.number(item.getTlg_au()));
		txtTlg_da.setText(Formats.number(item.getTlg_da()));
		txtTong_tlg.setText(Formats.number(item.getTong_tlg()));
		txtTien_cong.setText(Formats.money(item.getTien_cong()));
		txtTien_da.setText(Formats.money(item.getTien_da()));
		txtGia_au.setText(Formats.money(get_GiaAU(item.getVtID(), muaban)));
		txtGia_ban11.setText(Formats.money(item.getGia_ban11()));
		txtHlg_au.setText(Formats.percent(item.getHlg_au()));

		txtNameItem.setTag(item);
		txtThanh_tien.setText(Formats.money_round(thanhtien));
		if (item.getVtID().length() < 5) {
			txtSo_luong.setEnabled(false);
		}
		txtTlg_au.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				if (item.getVtID().length() < 5) {
					txtSo_luong.setText(s.toString());
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		if (muaban.equals("GIABAN")) {
			rboBan.setChecked(true);
			rboBan.setFocusable(true);
		} else {
			rboMua.setChecked(true);
			rboMua.setFocusable(true);
		}
		itemDialog = builder.create();
		itemDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		itemDialog.show();
		btnAdd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(WebService.checkTonKho(getActivity(),item.getVtID()) <= 0 && muaban.equals("GIABAN"))
				{
					Toast.makeText(getActivity(), R.string.tonkho_alert, Toast.LENGTH_LONG).show();
					return;		
				}
			
				// TODO Auto-generated method stub
				if (checkChangeItem(item)) {
					progressDialog = new ProgressDialog(getActivity());
					progressDialog.setMessage(getResources().getString(R.string.alert_waiting));
					progressDialog.show();
					item.setTlg_au(Double.valueOf(txtTlg_au.getText().toString().replace(",", "")));
					item.setTlg_da(Double.valueOf(txtTlg_da.getText().toString().replace(",", "")));
					item.setTong_tlg(Double.valueOf(txtTong_tlg.getText().toString().replace(",", "")));
					item.setTien_cong(Double.valueOf(txtTien_cong.getText().toString().replace(",", "")));
					item.setTien_da(Double.valueOf(txtTien_da.getText().toString().replace(",", "")));
					item.setGia_au(Double.valueOf(txtGia_au.getText().toString().replace(",", "")));
					item.setGia_ban11(Double.valueOf(txtGia_ban11.getText().toString().replace(",", "")));
					item.setHlg_au(Double.valueOf(txtHlg_au.getText().toString().replace(",", "")));
					Message m = new Message();
					m.obj = item;
					m.what = 1;
					m.arg1 = action;
					m.arg2 = position;
					handler.sendMessage(m);
				} else {
					Double thanhtien = Double.valueOf(Math.round(((Double.valueOf(txtSo_luong.getText().toString().replace(",", "")) * Double.valueOf(txtGia_ban11.getText().toString().replace(",", ""))) / 1000) * 1000));
					if (action == ACTION_NEW_ITEM) {
						addItem(item, rboMua.isChecked() ? "MUAHANG" : "BANHANG", Double.valueOf(txtSo_luong.getText().toString()), thanhtien);
					} else {
						editItem(item, rboMua.isChecked() ? "MUAHANG" : "BANHANG", Double.valueOf(txtSo_luong.getText().toString()), thanhtien, position);
					}
					itemDialog.dismiss();
				}
			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				itemDialog.dismiss();
			}
		});
		btnCal.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (checkChangeItem(item)) {
					progressDialog = new ProgressDialog(getActivity());
					progressDialog.setMessage(getResources().getString(R.string.alert_waiting));
					progressDialog.show();
					item.setTlg_au(Double.valueOf(txtTlg_au.getText().toString().replace(",", "")));
					item.setTlg_da(Double.valueOf(txtTlg_da.getText().toString().replace(",", "")));
					item.setTong_tlg(Double.valueOf(txtTong_tlg.getText().toString().replace(",", "")));
					item.setTien_cong(Double.valueOf(txtTien_cong.getText().toString().replace(",", "")));
					item.setTien_da(Double.valueOf(txtTien_da.getText().toString().replace(",", "")));
					item.setGia_au(Double.valueOf(txtGia_au.getText().toString().replace(",", "")));
					item.setGia_ban11(Double.valueOf(txtGia_ban11.getText().toString().replace(",", "")));
					item.setHlg_au(Double.valueOf(txtHlg_au.getText().toString().replace(",", "")));
					Message m = new Message();
					m.obj = item;
					m.what = 2;
					m.arg1 = action;
					m.arg2 = position;
					handler.sendMessage(m);
				} else {
					Double so_luong = Double.valueOf(txtSo_luong.getText().toString().toString().replace(",", ""));
					txtThanh_tien.setText(Formats.money_round(so_luong * Double.valueOf(txtGia_ban11.getText().toString().replace(",", ""))));
				}
			}
		});
	}

	private void addItem(Item i, String ctid, Double soluong, Double thanhtien) {
		arrItem.add(i);
		VoucherDetail vd = new VoucherDetail();
		vd.setFK_VtID(i.getVtID());
		vd.setVtName(i.getVtName());
		vd.setFK_DvtID(i.getFK_DvtID());
		vd.setCtID1(ctid);
		vd.setTlg_au(i.getTlg_au());
		vd.setTlg_da(i.getTlg_da());
		vd.setHlg_au(i.getHlg_au());
		vd.setTong_tlg(i.getTong_tlg());
		vd.setTien_cong(i.getTien_cong());
		vd.setTien_da(i.getTien_da());
		vd.setGia(i.getGia_ban11());
		vd.setGia_au(i.getGia_au());
		vd.setTien(Double.valueOf(Math.round(thanhtien / 1000) * 1000));
		vd.setSo_luong(soluong);
		vd.setFK_TkID_dt(i.getFK_TkID_dt());
		vd.setFK_TkID_gv(i.getFK_TkID_gv());
		vd.setFK_TkID_vt(i.getFK_TkID_vt());
		arrVoucherDetail.add(vd);
		adapter.swapData(arrVoucherDetail);
		callist();
	}

	private void editItem(Item i, String ctid, Double soluong, Double thanhtien, int position) {
		arrItem.get(position).setTlg_au(i.getTlg_au());
		arrItem.get(position).setTlg_da(i.getTlg_da());
		arrItem.get(position).setTong_tlg(i.getTong_tlg());
		arrItem.get(position).setHlg_au(i.getHlg_au());
		arrItem.get(position).setTien_cong(i.getTien_cong());
		arrItem.get(position).setTien_da(i.getTien_da());
		arrItem.get(position).setGia_au(i.getGia_au());
		arrItem.get(position).setGia_ban11(i.getGia_ban11());

		arrVoucherDetail.get(position).setFK_VtID(i.getVtID());
		arrVoucherDetail.get(position).setVtName(i.getVtName());
		arrVoucherDetail.get(position).setFK_DvtID(i.getFK_DvtID());
		arrVoucherDetail.get(position).setCtID1(ctid);
		arrVoucherDetail.get(position).setTlg_au(i.getTlg_au());
		arrVoucherDetail.get(position).setTlg_da(i.getTlg_da());
		arrVoucherDetail.get(position).setHlg_au(i.getHlg_au());
		arrVoucherDetail.get(position).setTong_tlg(i.getTong_tlg());
		arrVoucherDetail.get(position).setTien_cong(i.getTien_cong());
		arrVoucherDetail.get(position).setTien_da(i.getTien_da());
		arrVoucherDetail.get(position).setGia(i.getGia_ban11());
		arrVoucherDetail.get(position).setGia_au(i.getGia_au());
		arrVoucherDetail.get(position).setTien(Double.valueOf(Math.round(thanhtien / 1000) * 1000));
		arrVoucherDetail.get(position).setSo_luong(soluong);
		adapter.swapData(arrVoucherDetail);
		callist();
	}

	private boolean checkChangeItem(Item i) {
		double tlg_au = Double.parseDouble(txtTlg_au.getText().toString().replace(",", ""));
		if (tlg_au != i.getTlg_au().doubleValue()) {
			return true;
		}
		double tlg_da = Double.parseDouble(txtTlg_da.getText().toString().replace(",", ""));
		if (tlg_da != i.getTlg_da().doubleValue()) {
			return true;
		}
		double tong_tlg = Double.parseDouble(txtTong_tlg.getText().toString().replace(",", ""));
		if (tong_tlg != i.getTong_tlg().doubleValue()) {
			return true;
		}
		double tien_cong = Double.parseDouble(txtTien_cong.getText().toString().replace(",", ""));
		if (tien_cong != i.getTien_cong().doubleValue()) {
			return true;
		}
		double tien_da = Double.parseDouble(txtTien_da.getText().toString().replace(",", ""));
		if (tien_da != i.getTien_da().doubleValue()) {
			return true;
		}
		double gia_au = Double.parseDouble(txtGia_au.getText().toString().replace(",", ""));
		if (gia_au != i.getGia_au().doubleValue()) {
			return true;
		}
		double gia_ban = Double.parseDouble(txtGia_ban11.getText().toString().replace(",", ""));
		if (gia_ban != i.getGia_ban11().doubleValue()) {
			return true;
		}
		double hlg_au = Double.parseDouble(txtHlg_au.getText().toString().replace(",", ""));
		if (hlg_au != i.getHlg_au().doubleValue()) {
			return true;
		}
		return false;
	}

	Handler handler = new Handler(new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Item i = (Item) msg.obj;
			Double giaban = WebService.calPrice(getActivity(), i, rboBan.isChecked() ? "GIABAN" : "GIAMUA");
			txtGia_ban11.setText(Formats.money(giaban));
			i.setGia_ban11(giaban);
			Double so_luong = Double.valueOf(txtSo_luong.getText().toString());

			txtThanh_tien.setText(Formats.money_round(so_luong * giaban));
			txtNameItem.setTag(i);
			progressDialog.dismiss();
			if (msg.what == 1) {

				if (msg.arg1 == ACTION_NEW_ITEM) {
					addItem(i, rboMua.isChecked() ? "MUAHANG" : "BANHANG", Double.valueOf(txtSo_luong.getText().toString().replace(",", "")), Double.valueOf(txtThanh_tien.getText().toString().replace(",", "")));
				} else {
					editItem(i, rboMua.isChecked() ? "MUAHANG" : "BANHANG", Double.valueOf(txtSo_luong.getText().toString().replace(",", "")), Double.valueOf(txtThanh_tien.getText().toString().replace(",", "")), msg.arg2);
				}
				itemDialog.dismiss();
			}
			return false;
		}
	});

}
